<?php
session_start();
set_include_path('./../../nearestCaches/library' . PATH_SEPARATOR . get_include_path());
$PEAR_PATH = 'PEAR.php';
include ('Request/Request.php');
include "functions.php";
$lang = getLang();
$versionInt = getClientIntVersion();

global $viewstate;
global $postback;
global $cookie;

//get page of selected cache
$url = "http://www.geocaching.com/seek/cache_details.aspx?guid=".$_GET['guid'];
$req = & new HTTP_Request($url);
$req->setMethod(HTTP_REQUEST_METHOD_GET);
$req->addHeader('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6');
$req->addCookie('ASP.NET_SessionId', $_SESSION['cookie']);
$req->sendRequest();
$response = $req->getResponseBody();

//error if cache is archived or disabled
$error = '';
if(strpos($response, '<span id="ctl00_ContentBody_ErrorText"', $position)) {
    if (strpos($response, 'archived', $position)) {
        $error = "archived!";
    } elseif (strpos($response, 'unavailable', $position)) {
        $error = "disabled!";
    }
}

if(!empty($error)) { //error output
    $html = '<?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
            <html>
                <head>
                    <title>Error</title>
                </head>
                <body class="alert">
                    <p>Cache '.$error.'</p>
                </body>
            </html>';
    echo $html;
} else {	//output if no error
    $position = 0;
    $cacheName = parseBetween('<span id="ctl00_ContentBody_CacheName">', '</span>');
    $cacheName = html_entity_decode($cacheName,ENT_NOQUOTES,"UTF-8");
    $html = '<?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
            <html>
                <head>
                    <title>';
    if($_GET['show'] == 'listing') { //show Listing
        $shortDescription = (!strstr($response, 'ShortDescription')) ? '' : parseBetween('<span id="ctl00_ContentBody_ShortDescription">', '</span>');
        $longDescription = parseBetween('<span id="ctl00_ContentBody_LongDescription">', '</span>');
        if ($versionInt < 151) {
            $shortDescription = removeHTML($shortDescription, true);
            $longDescription = trim(removeHTML($longDescription, true));
        }
        else
        {
            $shortDescription = adjustHTML($shortDescription);
            $longDescription = adjustHTML($longDescription);
        }

        $html .= $lang['listing'].'</title></head><body>'.html_entity_decode($shortDescription, ENT_QUOTES, 'UTF-8')."<br />".html_entity_decode($longDescription, ENT_QUOTES, 'UTF-8');
    } elseif($_GET['show'] == 'hint') { //show Hint
        $hint = (!strstr($response, 'id="ctl00_ContentBody_Hints"')) ? $lang['no_hint'] : removeHTML(str_rot13(parseBetween('<span id="ctl00_ContentBody_Hints" class="displayMe">', '</span>')), false);
        $html .= $lang['hint'].'</title></head><body><p>'.$hint.'</p>';
    } elseif($_GET['show'] == 'aw') { //additional waypoints
        //parsing additional waypoints table
        $position = 0;
        $response = parseBetween('<strong>Additional Waypoints</strong>', '</table>');
        $table = array();
        $i = 0;
        while($position = strpos(' '.$response, '<tr')) {
            $allTable = $response;
            $position = 0;
            $tr = parseBetween('<tr bgcolor', '</tr>');
            $tr = substr($tr, (strpos($tr, '>')+1));
            $table[$i] = array();
            while($position = strpos(' '.$tr, '<td')) {
                $response = $tr;
                $position = 0;
                $td = parseBetween('<td', '</td>');
                $td = substr($td, (strpos($td, '>')+1));

                $table[$i][] = $td;
                $tr = substr($tr, (strpos($tr, '</td>')+5));
            }

            $response = substr($allTable, (strpos($allTable, '<tr bgcolor')+11));
            $response = substr($response, (strpos($response, '</tr>')+5));
            $i++;
        }
        //output
        $html .= $lang['additional_waypoints'].'</title></head><body class=\"list\"><ul>';
        foreach($table as $aw) {
            if(!empty($aw)&&isset($aw[3])) {
                $position = 0;
                $response = $aw[4];
                $awName = parseBetween('>', '</a>');
                $html .= '<li><a href="'.SERVICE_URL.'aw.php?guid='.$_GET['guid'].'&lookup='.$aw[3].'" class="listItem">'.$awName.'</a></li>'."\n";
            }
        }
        $html .= '</ul>';
    } elseif($_GET['show'] == 'logs') { //last logs
        //parsing last logs table
        $position = 0;
        $response = parseBetween('<table class="LogsTable Table">', '</table></span></p>');

        $table = array();
        $i = 0;
        while($position = strpos(' '.$response, '<tr')) {
            $allTable = $response;
            $position = 0;
            $tr = parseBetween('<tr', '</tr>');
            $tr = substr($tr, (strpos($tr, '>')+1));
            $table[$i] = array();
            while($position = strpos(' '.$tr, '<td')) {
                $response = $tr;
                $position = 0;
                $td = parseBetween('<td', '</td>');
                $td = substr($td, (strpos($td, '>')+1));

                $table[$i][] = $td;
                $tr = substr($tr, (strpos($tr, '</td>')+5));
            }

            $response = substr($allTable, (strpos($allTable, '<tr')+11));
            $response = substr($response, (strpos($response, '</tr>')+5));
            $i++;
        }

        $logs = array();
        $i=0;
        foreach($table as $log) {
            if(!empty($log[0]) && $log[0] != 'Cache Logs') {
                $position = 0;
                $response = $log[0];
                $logs[$i]['type'] = parseBetween('/icons/', '.gif');
                $logs[$i]['date'] = parseBetween('>&nbsp;', ' by <a');
                $position += 70;
                $logs[$i]['author'] = parseBetween('>', '</a></strong>');
                $logs[$i]['log'] = removeHTML(parseBetween('<br />', '<br /><br /><small><a href="log.aspx?LUID='), true);
                $i++;
            }
        }
        $html .= $lang['show_logs'].'</title></head><body>';
        foreach($logs as $log) {
            if($lang['yes'] == 'Ano') { //date for Czech language
                $date = explode(' ',$log['date']);
                $date = $date[1].'. '.strTr($date[0], array('January' => 'Leden', 'February' => 'Únor', 'March' => 'Březen', 'April' => 'Duben', 'May' => 'Květen', 'June' => 'Červen', 'July' => 'Červenec', 'August' => 'Srpen', 'September' => 'Září', 'October' => 'Říjen', 'November' => 'Listopad', 'December' => 'Prosinec'));
            } else {
                $date = $log['date'];
            }
            $html .= '<p>'.$date.': '.$lang[$log['type']].' '.$lang['by'].' '.$log['author'].'</p><p>'.$log['log'].'</p><br />'."\n";
        }
    } else {	//list with link to cache informations and navigation
        //test if this cache have additional waypoints
        $isAW = strstr($response, '<strong>Additional Waypoints</strong>');
        $isInventory = strstr($response, 'There are no Travel Bugs in this cache');

        //getting cache coordinates and other info needed for navigate
        $position = 0;
        $coords = parseBetween('<span id="ctl00_ContentBody_LatLon" style="font-weight:bold;">', '</span>');
        $coords = explode(' ', $coords);

        $lat_h = $coords[0];
        $lat_d = substr($coords[1], 0, 2);
        $lat_m = $coords[2];

        $lon_h = $coords[3];
        $lon_d = substr($coords[4], 0, 3);
        $lon_m = $coords[5];

        //converting coordinates to requested format
        $lat = latDMtoD($lat_h, $lat_d, $lat_m);
        $lon = lonDMtoD($lon_h, $lon_d, $lon_m);

        //cache info which we add to kml
        $position = 0;
        $oldResponse = $response;
        $response = parseBetween('<!-- Begin Cache Code Widget -->', '<!-- End Cache Code Widget -->');
        $position = 0;
        $waypoint = parseBetween('<p>', '</p>');
        $position = 0;
        $response = $oldResponse;
        $response = parseBetween('<a href="/about/cache_types.aspx" target="_blank">', '</em>');
        $position = 0;
        $typeNumber = parseBetween('WptTypes/', '.gif');
        $type = parseBetween('ALT="', '" border=0');
        $cacheName = parseBetween('<span id="ctl00_ContentBody_CacheName">', '</span>');
	$html .= $cacheName;
        $cacheName = urlencode(html_entity_decode($cacheName,ENT_NOQUOTES,"UTF-8"));

        $html .= '</title></head><body class="list">
                    <ul>
                        <li><a href="'.SERVICE_URL.'navigate.php?show=simple&guid='.$_GET['guid'].'" class="listItem">'.$lang['view'].'</a></li>
                        <li><a href="locify://navigation?lat='.$lat.'&lon='.$lon.'&name='.$cacheName.'" class="listItem">'.$lang['navigate'].'</a></li>
                        <li><a href="locify://maps?lat='.$lat.'&lon='.$lon.'&name='.$cacheName.'&desc=Geocache" class="listItem">'.$lang['show_on_map'].'</a></li>
                        <li><a href="'.SERVICE_URL.'cache.php?show=listing&amp;guid='.$_GET['guid'].'" class="listItem">'.$lang['show_listing'].'</a></li>
                        <li><a href="'.SERVICE_URL.'cache.php?show=hint&amp;guid='.$_GET['guid'].'" class="listItem">'.$lang['show_hint'].'</a></li>
                        <li><a href="'.SERVICE_URL.'navigate.php?show=kml&guid='.$_GET['guid'].'" class="listItem">'.$lang['download'].'</a></li>'."\n";
        $html .= '<li><a href="'.SERVICE_URL.'cache.php?show=logs&amp;guid='.$_GET['guid'].'" class="listItem">'.$lang['show_logs'].'</a></li>';
        $html .= '<li><a href="'.SERVICE_URL.'log.php?guid='.$_GET['guid'].'" class="listItem">'.$lang['log_visit'].'</a></li>'."\n";
        if($isAW) $html .= '<li><a href="'.SERVICE_URL.'cache.php?show=aw&amp;guid='.$_GET['guid'].'" class="listItem">'.$lang['additional_waypoints'].'</a></li>'."\n";
        if(!$isInventory) $html .= '<li><a href="'.SERVICE_URL.'inventory.php?guid='.$_GET['guid'].'" class="listItem">'.$lang['inventory'].'</a></li>'."\n";
        $html .= '<li><a href="'.SERVICE_URL.'waypoint_navigate.php" class="listItem">'.$lang['wpnav'].'</a></li>';
        $html .= '</ul>';
    }
    $html .= "\n</body>
            </html>";
    echo $html;
}
?>
